package com.takeoutsystem.controller;


import com.alibaba.fastjson.JSONObject;
import com.takeoutsystem.bean.User;
import com.takeoutsystem.config.property.WxApplicationProperties;
import com.takeoutsystem.service.UserService;
import com.takeoutsystem.support.RestTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


/**
 * 微信用户登录/注册控制类
 * @author codeNoob2281
 */
@RestController
@RequestMapping("/wx")
public class WxUserController {

    //config properties
    @Autowired
    WxApplicationProperties wxApplicationProperties;

    UserService userService;
    @Autowired
    public WxUserController(UserService userService){
        this.userService=userService;
    }


    /**
     * 获取小程序发送的code，换取openId
     *
     * @param code 微信登录code
     * @return 用户信息
     */
    @GetMapping("/login")
    public Map<String,Object> login(@RequestParam("code") String code, HttpSession session) {

        Map<String,Object> model=new HashMap<String,Object>();
        //登录校验的url
        String url="https://api.weixin.qq.com/sns/jscode2session";
        //post参数，发送code并获取openId
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
        param.add("appid",wxApplicationProperties.getAppId());
        param.add("secret", wxApplicationProperties.getSecret());
        param.add("js_code", code);
        param.add("grant_type", "authorization_code");
        JSONObject json = RestTemplateUtil.doPost(url,param);
        //获取openid
        String openId=json.getString("openid");
        //将用户id存于session种用于验证是否登录
        session.setAttribute("userId",openId);
        //查询用户是否存在
        User user=userService.getById(openId);
        //用户不存在，创建新用户
        if(user==null){
            User newUser=new User();
            newUser.setOpenId(openId);
            userService.save(newUser);
            model.put("openId",newUser.getOpenId());
            model.put("userName",null);
            model.put("telNumber",null);
            model.put("userType",null);
            model.put("isNewUser",true);
            return model;
        }

        //用户存在。将用户类型存于session种用于权限验证
        //session.setAttribute("userType",user.getUserType());

        //用户已存在，返回用户信息
        model.put("openId",user.getOpenId());
        model.put("userName",user.getUserName());
        model.put("telNumber",user.getTelNumber());
        model.put("userType",user.getUserType());
        model.put("isNewUser",false);
        return model;
    }


    /**
     * 修改用户信息，主要有处理以下业务：
     * 1.修改昵称;
     * 2.修改绑定的手机号;
     * 3.首次绑定用户类型(已绑定类型的用户不可再次修改用户类型);
     * 根据mybatis-plus官方文档的描述,user实例中值为null的属性不会被更新到数据库
     * @param user 修改后的用户类
     * @return 修改结果
     */
    @PostMapping("/changeUserInfo")
    public Boolean changeTel(User user){
          return  userService.updateById(user);
    }


}
